<template>
    <main class="main-page" id="">
        <section class="page-section q-pa-md">
            <div class="container-fluid">
                <div class="grid ">
                    <div class="col comp-grid">
                        <div class=" text-lg font-bold text-primary">
                            {{ $t('home') }}
                        </div>
                    </div>
                    <div class="col-sm-4 col-md-4 col-12 comp-grid" v-if="auth.canView('blocks/info')">
                        <div class="">
                            <div class="grid">
                                <!-- 最新区块卡片 -->
                                <div class="col-12 md:col-6 lg:col-4 comp-grid">
                                    <Card class="shadow-2 h-full">
                                        <template #title>
                                            <div class="flex align-items-center gap-2">
                                                <i class="pi pi-cube"></i>
                                                <span>最新区块</span>
                                            </div>
                                        </template>
                                        <template #content>
                                            <div v-if="blockData" class="grid">
                                                <!-- 区块高度 -->
                                                <div class="col-12 mb-3">
                                                    <div class="text-500 font-medium">区块高度</div>
                                                    <div class="text-900 font-bold text-xl">
                                                        {{ blockData.blockNumber }}
                                                    </div>
                                                </div>
                                                <!-- 区块哈希 -->
                                                <div class="col-12 mb-3">
                                                    <div class="text-500 font-medium">区块哈希</div>
                                                    <div class="flex align-items-center gap-2">
                                                        <span class="text-900 font-mono text-sm truncate">
                                                            {{ truncateHash(blockData.blockHash) }}
                                                        </span>
                                                        <Button icon="pi pi-copy" class="p-button-text p-button-sm"
                                                            v-tooltip="'复制哈希'" @click="copyHash(blockData.blockHash)" />
                                                    </div>
                                                </div>
                                                <div class="col-12 grid">
                                                    <!-- 交易数量 -->
                                                    <div class="col-6">
                                                        <div class="text-500 font-medium">交易数量</div>
                                                        <Tag :value="blockData.transactionCount" severity="info" />
                                                    </div>
                                                    <!-- 矿工地址 -->
                                                    <div class="col-6">
                                                        <div class="text-500 font-medium">矿工地址</div>
                                                        <div class="flex align-items-center gap-2">
                                                            <span class="text-900 font-mono text-sm truncate">
                                                                {{ truncateHash(blockData.miner) }}
                                                            </span>
                                                            <Button icon="pi pi-copy" class="p-button-text p-button-sm"
                                                                v-tooltip="'复制哈希'" @click="copyHash(blockData.miner)" />
                                                        </div>
                                                    </div>
                                                </div>
                                                <!-- 时间戳 -->
                                                <div class="col-12 mt-3">
                                                    <div class="text-500 font-medium">生成时间</div>
                                                    <div class="flex align-items-center gap-2">
                                                        <i class="pi pi-clock"></i>
                                                        <span>{{ formatDate(blockData.timestamp) }}</span>
                                                    </div>
                                                </div>
                                            </div>
                                            <Skeleton v-else height="150px"></Skeleton>
                                        </template>
                                        <template #footer>
                                            <Button label="刷新数据" icon="pi pi-refresh" @click="getBlockData"
                                                :loading="loading" class="p-button-sm w-full" />
                                        </template>
                                    </Card>
                                </div>
                                <!-- 区块统计卡片 -->
                                <div class="col-12 md:col-6 lg:col-4 comp-grid">
                                    <Card class="bg-blue-50 border-blue-100 h-full">
                                        <template #title>
                                            <div class="flex align-items-center gap-2 text-blue-800">
                                                <i class="pi pi-chart-bar"></i>
                                                <span>区块统计</span>
                                            </div>
                                        </template>
                                        <template #content>
                                            <div v-if="blockData" class="grid">
                                                <div class="col-12 mb-4">
                                                    <div class="text-blue-600 font-medium">Gas 使用率</div>
                                                    <ProgressBar :value="(blockData.gasUsed / blockData.gasLimit) * 100"
                                                        :showValue="false" class="h-1rem" />
                                                    <div class="text-900 text-sm mt-1">
                                                        已用 {{ blockData.gasUsed }} / 上限 {{ blockData.gasLimit }}
                                                    </div>
                                                </div>
                                                <div class="col-12">
                                                    <div class="text-blue-600 font-medium">父区块哈希</div>
                                                    <div class="flex align-items-center gap-2">
                                                        <span class="text-900 font-mono text-xs truncate">
                                                            {{ truncateHash(blockData.parentHash) }}
                                                        </span>
                                                        <Button icon="pi pi-copy" class="p-button-text p-button-sm"
                                                            v-tooltip="'复制哈希'"
                                                            @click="copyHash(blockData.parentHash)" />
                                                    </div>
                                                </div>
                                            </div>
                                            <Skeleton v-else height="100px"></Skeleton>
                                        </template>
                                    </Card>
                                </div>
                                <!-- 已部署合约列表卡片 -->
                                <div class="col-12 md:col-6 lg:col-4 comp-grid">
                                    <Card class="shadow-1 h-full">
                                        <template #title>
                                            <div class="flex align-items-center gap-2">
                                                <i class="pi pi-file"></i>
                                                <span>已部署合约</span>
                                            </div>
                                        </template>
                                        <template #content>
                                            <div v-if="contractsLoading" class="text-center py-4">
                                                <ProgressSpinner style="width: 50px; height: 50px" />
                                            </div>
                                            <div v-else>
                                                <div v-if="contracts.length === 0" class="text-center text-500 py-4">
                                                    暂无已部署合约
                                                </div>
                                                <div v-else class="contract-list"
                                                    style="max-height: 300px; overflow-y: auto;">
                                                    <div v-for="contract in contracts" :key="contract.id"
                                                        class="mb-3 p-3 border-round surface-100">
                                                        <div class="flex justify-content-between align-items-center">
                                                            <div>
                                                                <div class="font-bold">{{ contract.contract_name }}
                                                                </div>
                                                                <div class="text-sm text-500">{{ contract.version }}
                                                                </div>
                                                            </div>
                                                            <Tag :value="contract.category"
                                                                :severity="contract.category === 'data' ? 'info' : 'warning'" />
                                                        </div>
                                                        <div class="mt-2">
                                                            <div class="flex align-items-center gap-2">
                                                                <span class="font-mono text-sm truncate">
                                                                    {{ truncateHash(contract.contract_address) }}
                                                                </span>
                                                                <Button icon="pi pi-copy"
                                                                    class="p-button-text p-button-sm"
                                                                    @click="copyHash(contract.contract_address)" />
                                                            </div>
                                                        </div>
                                                        <div class="mt-2 text-xs text-500">
                                                            {{ formatDate(contract.date_created) }}
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </template>
                                        <template #footer>
                                            <Button label="查看全部合约" icon="pi pi-list"
                                                class="p-button-sm w-full p-button-outlined"
                                                @click="viewAllContracts" />
                                        </template>
                                    </Card>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-4 col-md-4 col-12 comp-grid" v-if="auth.canView('smartcontracts/deploy')">
                        <div class="">
                            <!-- 教务人员管理卡片 -->
                            <div class="col-12 comp-grid mb-4">
                                <Card class="shadow-2">
                                    <template #title>
                                        <div class="flex align-items-center gap-2">
                                            <i class="pi pi-users"></i>
                                            <span>教务人员管理</span>
                                        </div>
                                    </template>
                                    <template #content>
                                        <!-- 添加教务人员表单 -->
                                        <div class="mb-4">
                                            <div class="text-500 font-medium mb-2">添加教务人员</div>
                                            <div class="p-inputgroup">
                                                <InputText v-model="registrarForm.address" 
                                                    placeholder="输入教务人员钱包地址" 
                                                    class="w-full" />
                                                <Button icon="pi pi-plus" 
                                                    class="p-button-text" 
                                                    @click="addRegistrar"
                                                    :loading="addingRegistrar" />
                                            </div>
                                        </div>

                                        <!-- 教务人员列表 -->
                                        <div class="registrar-list" style="max-height: 300px; overflow-y: auto;">
                                            <div v-if="registrarsLoading" class="text-center py-4">
                                                <ProgressSpinner style="width: 50px; height: 50px" />
                                            </div>
                                            <div v-else>
                                                <div v-if="registrars.length === 0" class="text-center text-500 py-4">
                                                    暂无教务人员
                                                </div>
                                                <div v-else>
                                                    <div v-for="registrar in registrars" :key="registrar.address"
                                                        class="mb-3 p-3 border-round surface-100">
                                                        <div class="flex justify-content-between align-items-center">
                                                            <div>
                                                                <div class="font-bold">{{ registrar.name }}</div>
                                                                <div class="text-sm text-500">{{ registrar.personalId }}</div>
                                                            </div>
                                                            <Button icon="pi pi-trash" 
                                                                class="p-button-text p-button-danger" 
                                                                @click="removeRegistrar(registrar.address)"
                                                                :loading="removingRegistrar === registrar.address" />
                                                        </div>
                                                        <div class="mt-2">
                                                            <div class="flex align-items-center gap-2">
                                                                <span class="font-mono text-sm truncate">
                                                                    {{ truncateHash(registrar.address) }}
                                                                </span>
                                                                <Button icon="pi pi-copy" 
                                                                    class="p-button-text p-button-sm"
                                                                    @click="copyHash(registrar.address)" />
                                                            </div>
                                                        </div>
                                                        <div class="mt-2 text-xs text-500">
                                                            添加时间: {{ formatDate(registrar.addedAt) }}
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </template>
                                </Card>
                            </div>
                            <!-- 新增合约部署卡片 -->
                            <div class="col-sm-4 col-md-4 col-12 comp-grid">
                                <Card class="shadow-2">
                                    <template #title>
                                        <div class="flex align-items-center gap-2">
                                            <i class="pi pi-file-edit"></i>
                                            <span>部署智能合约</span>
                                        </div>
                                    </template>
                                    <template #content>
                                        <div class="grid">
                                            <!-- 合约文件上传 -->
                                            <div class="col-12 mb-3">
                                                <label class="block text-500 font-medium mb-2">合约文件 (.sol)</label>
                                                <Uploader ref="contractUploader"
                                                    upload-path="fileuploader/upload/contract_file"
                                                    v-model="deployForm.contract_file_path" :fileLimit="1"
                                                    :maxFileSize="5000000" accept=".sol" :multiple="false"
                                                    :label="$t('chooseFilesOrDropFilesHere')"
                                                    @uploadComplete="onContractUploadComplete"
                                                    @uploadError="onUploadError" />
                                                <small v-if="deployForm.contract_file_path" class="text-500">
                                                    已上传合约文件
                                                </small>
                                            </div>
                                            <!-- 合约名称 -->
                                            <div class="col-12 mb-3">
                                                <label class="block text-500 font-medium mb-2">合约名称</label>
                                                <InputText v-model="deployForm.contract_name"
                                                    placeholder="例如: MyContract" class="w-full" />
                                            </div>
                                            <!-- 合约版本 -->
                                            <div class="col-12 mb-3">
                                                <label class="block text-500 font-medium mb-2">版本</label>
                                                <InputText v-model="deployForm.version" placeholder="例如: 1.0.0"
                                                    class="w-full" />
                                            </div>
                                            <!-- 合约类别 -->
                                            <div class="col-12 mb-3">
                                                <label class="block text-500 font-medium mb-2">类别</label>
                                                <Dropdown v-model="deployForm.category" :options="['data', 'operation', 'proxy']"
                                                    optionLabel="" placeholder="选择合约类别" class="w-full" 
                                                    @change="onCategoryChange" />
                                            </div>
                                            <!-- 存储合约地址（仅当类别为operation时显示） -->
                                            <div v-if="deployForm.category === 'operation'" class="col-12 mb-3">
                                                <label class="block text-500 font-medium mb-2">存储合约地址</label>
                                                <div class="p-inputgroup">
                                                    <InputText v-model="deployForm.storage_address" 
                                                        placeholder="输入存储合约地址" 
                                                        class="w-full" />
                                                    <Button icon="pi pi-search" 
                                                        class="p-button-text" 
                                                        @click="showStorageContracts" />
                                                </div>
                                                <small class="text-500">请选择已部署的数据合约作为存储合约</small>
                                            </div>
                                            <!-- 构造函数参数 -->
                                            <div class="col-12 mb-3">
                                                <label class="block text-500 font-medium mb-2">构造函数参数 (JSON数组)</label>
                                                <Textarea v-model="deployForm.constructor_args" rows="3"
                                                    placeholder='例如: ["参数1", 123]' class="w-full" />
                                            </div>
                                            <!-- 合约描述 -->
                                            <div class="col-12 mb-3">
                                                <label class="block text-500 font-medium mb-2">描述 (可选)</label>
                                                <Textarea v-model="deployForm.description" rows="2" placeholder="合约功能描述"
                                                    class="w-full" />
                                            </div>
                                        </div>
                                    </template>
                                    <template #footer>
                                        <Button label="部署合约" icon="pi pi-send" @click="deployContract"
                                            :loading="deploying" class="p-button-sm w-full" :disabled="!canDeploy" />
                                    </template>
                                </Card>
                                <!-- 部署结果卡片 -->
                                <Card v-if="deployResult" class="mt-3 shadow-1">
                                    <template #title>
                                        <div class="flex align-items-center gap-2 text-green-700">
                                            <i class="pi pi-check-circle"></i>
                                            <span>部署结果</span>
                                        </div>
                                    </template>
                                    <template #content>
                                        <div class="grid">
                                            <div class="col-12 mb-2">
                                                <label class="text-500">合约名称:</label>
                                                <div class="font-bold">{{ deployResult.contract.name }}</div>
                                            </div>
                                            <div class="col-12 mb-2">
                                                <label class="text-500">合约地址:</label>
                                                <div class="flex align-items-center gap-2">
                                                    <span class="font-mono text-sm truncate">
                                                        {{ truncateHash(deployResult.contract.address) }}
                                                    </span>
                                                    <Button icon="pi pi-copy" class="p-button-text p-button-sm"
                                                        @click="copyHash(deployResult.contract.address)" />
                                                </div>
                                            </div>
                                            <div class="col-12 mb-2">
                                                <label class="text-500">版本:</label>
                                                <div>{{ deployResult.contract.version }}</div>
                                            </div>
                                            <div class="col-12 mb-2">
                                                <label class="text-500">类别:</label>
                                                <Tag :value="deployResult.category"
                                                    :severity="deployResult.category === 'data' ? 'info' : 'warning'" />
                                            </div>
                                            <div v-if="deployResult.contract.storage_address" class="col-12 mb-2">
                                                <label class="text-500">存储合约地址:</label>
                                                <div class="flex align-items-center gap-2">
                                                    <span class="font-mono text-sm truncate">
                                                        {{ truncateHash(deployResult.contract.storage_address) }}
                                                    </span>
                                                    <Button icon="pi pi-copy" class="p-button-text p-button-sm"
                                                        @click="copyHash(deployResult.contract.storage_address)" />
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <Button label="查看合约详情" icon="pi pi-external-link"
                                                    class="p-button-sm p-button-outlined w-full"
                                                    @click="viewContractDetails(deployResult.contract.id)" />
                                            </div>
                                        </div>
                                    </template>
                                </Card>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>

</template>
<script setup>
import { computed, ref, onMounted } from 'vue';
import { ApiService } from 'src/services/api';

import { useApp } from 'src/composables/app.js';

import { useAuth } from '@/composables/auth';

import { $t } from 'src/services/i18n';

const auth = useAuth();

const props = defineProps({
    pageName: {
        type: String,
        default: 'home',
    },
    routeName: {
        type: String,
        default: 'home',
    },
    isSubPage: {
        type: Boolean,
        default: false,
    },
});
const app = useApp();

const pageReady = ref(true);
const blockData = ref(null);
const loading = ref(false);
// 格式化日期为中文
const formatDate = (timestamp) => {
    return new Date(timestamp).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
};
// 获取区块数据
const getBlockData = async () => {
    try {
        loading.value = true;
        const response = await ApiService.get("blocks/info");
        blockData.value = response.data.data;
    } catch (e) {
        console.error('获取区块数据失败:', e);
    } finally {
        loading.value = false;
    }
};
// 哈希截断显示
const truncateHash = (hash) => {
    if (!hash) return '';
    return `${hash.substring(0, 8)}...${hash.substring(hash.length - 6)}`;
};
// 复制功能
const copyHash = async (hash) => {
    try {
        await navigator.clipboard.writeText(hash);
        app.flashMsg('复制 ', '复制成功', 'success');
    } catch (e) {
        app.flashMsg('复制 ', '复制失败', 'success');
    }
};
// 合约部署相关状态
const deploying = ref(false);
const contractUploader = ref(null);
const deployForm = ref({
    contract_file_path: '', // 存储上传后的文件路径
    contract_name: '',
    version: '',
    category: 'data',
    description: '',
    constructor_args: '[]'
});
const deployResult = ref(null);
// 计算属性：是否可以部署
const canDeploy = computed(() => {
    return deployForm.value.contract_file_path &&
        deployForm.value.contract_name &&
        deployForm.value.version &&
        deployForm.value.category;
});
// 文件上传完成回调
const onContractUploadComplete = (uploadedPaths) => {
    if (!uploadedPaths) {
        app.flashMsg('错误', '文件上传失败', 'error');
        return;
    }
    
    // 只取第一个文件路径（因为我们设置了fileLimit=1）
    const filePath = uploadedPaths.split(',')[0];
    if (!filePath) {
        app.flashMsg('错误', '文件路径无效', 'error');
        return;
    }

    // 更新文件路径
    deployForm.value.contract_file_path = filePath;

    // 自动从文件名提取合约名称
    const fileName = filePath.split('/').pop().replace('.sol', '');
    deployForm.value.contract_name = fileName;
};
// 上传错误处理
const onUploadError = (errorMsg) => {
    app.flashMsg('文件上传', errorMsg, 'error');
};
// 存储合约列表
const storageContracts = ref([]);
const showStorageContracts = async () => {
    try {
        const response = await ApiService.get('smartcontracts/index', {
            params: {
                category: 'data',
                limit: 10
            }
        });
        storageContracts.value = response.data.records;
        
        // 显示存储合约选择对话框
        // 这里需要根据你的UI框架添加对话框组件
    } catch (error) {
        console.error('获取存储合约列表失败:', error);
        app.flashMsg('错误', '获取存储合约列表失败', 'error');
    }
};
// 类别变更处理
const onCategoryChange = () => {
    if (deployForm.value.category !== 'operation') {
        deployForm.value.storage_address = '';
    }
};
// 部署合约
const deployContract = async () => {
    try {
        deploying.value = true;

        // 验证必填字段
        if (!deployForm.value.contract_file_path) {
            app.flashMsg('错误', '请上传合约文件', 'error');
            return;
        }
        if (!deployForm.value.contract_name) {
            app.flashMsg('错误', '请输入合约名称', 'error');
            return;
        }
        if (!deployForm.value.version) {
            app.flashMsg('错误', '请输入合约版本', 'error');
            return;
        }
        if (!deployForm.value.category) {
            app.flashMsg('错误', '请选择合约类别', 'error');
            return;
        }

        // 验证存储合约地址（如果是逻辑合约）
        if (deployForm.value.category === 'operation' && !deployForm.value.storage_address) {
            app.flashMsg('错误', '部署逻辑合约需要提供存储合约地址', 'error');
            return;
        }

        // 处理构造函数参数
        let constructorArgs = '[]';
        try {
            // 如果用户输入了构造函数参数，尝试解析
            if (deployForm.value.constructor_args && deployForm.value.constructor_args.trim()) {
                constructorArgs = JSON.stringify(JSON.parse(deployForm.value.constructor_args));
            }
        } catch (err) {
            app.flashMsg('错误', '构造函数参数格式错误，请使用有效的JSON数组格式', 'error');
            return;
        }

        // 创建FormData对象
        const formData = new FormData();
        formData.append('contract_file_path', deployForm.value.contract_file_path);
        formData.append('contract_name', deployForm.value.contract_name);
        formData.append('version', deployForm.value.version);
        formData.append('category', deployForm.value.category);
        formData.append('description', deployForm.value.description || '');
        formData.append('constructor_args', constructorArgs);
        if (deployForm.value.storage_address) {
            formData.append('storage_address', deployForm.value.storage_address);
        }

        // 调用API
        const response = await ApiService.post('smartcontracts/deploy', formData);

        // 更新部署结果
        deployResult.value = {
            contract: response.data.contract,
            compile: response.data.compile,
            category: response.data.contract.isUpgradeable?'operation':'data'
        };

        app.flashMsg('合约部署', response.data.message, 'success');

        // 重置表单
        deployForm.value.contract_file_path = '';
        deployForm.value.contract_name = '';
        deployForm.value.version = '';
        deployForm.value.category = 'data';
        deployForm.value.description = '';
        deployForm.value.constructor_args = '[]';
        deployForm.value.storage_address = '';
        if (contractUploader.value) {
            contractUploader.value = null; // 清除上传的文件
        }

        // 刷新合约列表
        await fetchContracts();

    } catch (error) {
        console.error('合约部署失败:', error);
        app.flashMsg('合约部署', error.message || '部署失败', 'error');
    } finally {
        deploying.value = false;
    }
};
// 查看合约详情
const viewContractDetails = (contractId) => {
    // 这里根据你的路由配置进行调整
    window.location.href = `/#/smartcontracts/view/${contractId}`;
};
// 新增合约列表相关状态
const contracts = ref([]);
const contractsLoading = ref(false);
// 获取合约列表
const fetchContracts = async () => {
    try {
        contractsLoading.value = true;
        const response = await ApiService.get('smartcontracts/index', {
            params: {
                limit: 3, // 只获取最新的3个合约
                order: 'created_at,desc'
            }
        });
        contracts.value = response.data.records;
    } catch (error) {
        console.error('获取合约列表失败:', error);
        app.flashMsg('错误', '获取合约列表失败', 'error');
    } finally {
        contractsLoading.value = false;
    }
};
// 查看全部合约
const viewAllContracts = () => {
    window.location.href = '/#/smartcontracts';
};
// 教务人员管理相关状态
const registrars = ref([]);
const registrarsLoading = ref(false);
const addingRegistrar = ref(false);
const removingRegistrar = ref(null);
const registrarForm = ref({
    address: ''
});

// 获取教务人员列表
const fetchRegistrars = async () => {
    try {
        registrarsLoading.value = true;
        const response = await ApiService.get('smartcontracts/registrars');
        registrars.value = response.data;
    } catch (error) {
        console.error('获取教务人员列表失败:', error);
        app.flashMsg('错误', '获取教务人员列表失败', 'error');
    } finally {
        registrarsLoading.value = false;
    }
};

// 添加教务人员
const addRegistrar = async () => {
    try {
        if (!registrarForm.value.address) {
            app.flashMsg('错误', '请输入教务人员地址', 'error');
            return;
        }

        addingRegistrar.value = true;
        await ApiService.post('smartcontracts/add-registrar', {
            addresses: [registrarForm.value.address]
        });

        app.flashMsg('成功', '添加教务人员成功', 'success');
        registrarForm.value.address = '';
        await fetchRegistrars();
    } catch (error) {
        console.error('添加教务人员失败:', error);
        app.flashMsg('错误', error.message || '添加失败', 'error');
    } finally {
        addingRegistrar.value = false;
    }
};

// 删除教务人员
const removeRegistrar = async (address) => {
    try {
        removingRegistrar.value = address;
        await ApiService.post('smartcontracts/remove-registrar', {
            address: address
        });

        app.flashMsg('成功', '删除教务人员成功', 'success');
        await fetchRegistrars();
    } catch (error) {
        console.error('删除教务人员失败:', error);
        app.flashMsg('错误', error.message || '删除失败', 'error');
    } finally {
        removingRegistrar.value = null;
    }
};

// 组件加载时自动获取数据
onMounted(() => {
    if (auth.canView('blocks/info')) {
        getBlockData();
        fetchContracts();
    }
    if (auth.canView('smartcontracts/deploy')) {
        fetchRegistrars();
    }
});

</script>
<style scoped></style>
